using Catalog.Application.Brands.Interfaces;
using Catalog.Application.CatalogItems.Commands;
using Catalog.Application.CatalogItems.Interfaces;
using Catalog.Application.Categorys.Interfaces;
using Catalog.Application.Interfaces;
using MediatR;

namespace Catalog.Application.CatalogItems.CommandHandlers;

public class UpdateCatalogItemCommandHandler : IRequestHandler<UpdateCatalogItemCommand, Unit>
{
    private readonly ICatalogItemRepository _catalogItemRepository;
    private readonly IBrandReadService _brandReadService;
    private readonly ICategoryReadService _categoryReadService;
    private readonly IUnitOfWork _unitOfWork;

    public UpdateCatalogItemCommandHandler(ICatalogItemRepository catalogItemRepository, IUnitOfWork unitOfWork, IBrandReadService brandReadService, ICategoryReadService categoryReadService)
    {
        _catalogItemRepository = catalogItemRepository;
        _brandReadService = brandReadService;
        _categoryReadService = categoryReadService;
        _unitOfWork = unitOfWork;
    }
    public async Task<Unit> Handle(UpdateCatalogItemCommand request, CancellationToken cancellationToken)
    {
        var catalogItem = await _catalogItemRepository.GetByIdAsync(request.id);
        if (catalogItem == null)
            throw new KeyNotFoundException("商品目录不存在！");
        if (await _brandReadService.ExistsAsync(request.newBrandId))
            throw new KeyNotFoundException("品牌不存在！");
        if (await _categoryReadService.ExistsAsync(request.newCategoryId))
            throw new KeyNotFoundException("种类不存在！");

        catalogItem.ChangeName(request.newName);
        catalogItem.ChangeDescription(request.newDescription);
        catalogItem.ChangePrice(request.newPrice);
        catalogItem.ChangeBrand(request.newBrandId);
        catalogItem.ChangeCategory(request.newCategoryId);

        await _unitOfWork.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}